package com.cutie.core.dao;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;

import com.cutie.core.util.ConfigReader;


/**
 * there is only one connection pool,that is ,only one dataSource inside<br/>
 * singleton pattern
 *
 */
public class DatabaseConnectionPool{
	
	private static String username = "root";
	private static String password = "hlp19921029";
	private static String driverName="com.mysql.jdbc.Driver";
	private static String dbUrl = "jdbc:mysql://127.0.0.1:3306/cutie?useUnicode=true&characterEncoding=utf8";
	private static DataSource dataSource;//application scope sharing
	
	static{
		try {
			new DatabaseConnectionPool();
			readConfig();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection() throws SQLException{
		return dataSource.getConnection();
	}
	
	private DatabaseConnectionPool(){
		dataSource = setupDataSource(dbUrl);
	}
	
	public DataSource setupDataSource(String connectURI) {
		BasicDataSource ds = new BasicDataSource();
		ds.setDriverClassName(driverName);
		ds.setUsername(username);
		ds.setPassword(password);
		ds.setUrl(connectURI);
		return ds;
	}
	public static void printDataSourceStates() {
		BasicDataSource bds = (BasicDataSource) dataSource;
		System.out.println("NumActive: " + bds.getNumActive());
		System.out.println("NumIdle: " + bds.getNumIdle());
	}

	public static void shutdownDataSource() throws SQLException {
		BasicDataSource bds = (BasicDataSource) dataSource;
		bds.close();
	}
	
	public static void readConfig() throws FileNotFoundException, IOException{
		ConfigReader reader = new ConfigReader("/config.properties");
		Properties prop = reader.readConfig();
		username = prop.getProperty("username");
		password = prop.getProperty("password");
		driverName = prop.getProperty("driverName");
		dbUrl = prop.getProperty("dbUrl");
		reader.close();
	}
}


